/**
 * 对话存储相关的自定义Hook
 */
import { useState, useEffect, useCallback } from 'react';
import { Message, SavedConversation, SnackbarState } from '../../../types/chat.ts';
import { ChatMessage } from '../../../utils/aiApi.ts';
import {
    saveConversation as saveConversationUtil,
    loadSavedConversations as loadSavedConversationsUtil,
    deleteConversation as deleteConversationUtil
} from '../../../utils/aiChat/conversationUtils.ts';

type SetSnackbarFn = React.Dispatch<React.SetStateAction<SnackbarState>>;

/**
 * 对话存储钩子 - 处理对话的保存、加载和删除功能
 * @param currentChapter 当前章节名称
 * @param setSnackbar 设置提示条状态的函数
 * @returns 对话存储相关方法和状态
 */
export const useConversationStorage = (
    currentChapter: string = 'general',
    setSnackbar: SetSnackbarFn
) => {
    const [savedConversations, setSavedConversations] = useState<SavedConversation[]>([]);
    const [isDialogOpen, setIsDialogOpen] = useState(false);

    // 获取本地存储中的对话
    const getStoredConversations = useCallback((): SavedConversation[] => {
        try {
            const storedConversations = localStorage.getItem('saved_conversations');
            return storedConversations ? JSON.parse(storedConversations) : [];
        } catch (error) {
            console.error('读取对话存储失败:', error);
            return [];
        }
    }, []);

    // 保存对话列表到本地存储
    const persistConversations = useCallback((conversations: SavedConversation[]) => {
        try {
            localStorage.setItem('saved_conversations', JSON.stringify(conversations));
        } catch (error) {
            console.error('保存对话失败:', error);
        }
    }, []);

    // 初始化时加载保存的对话
    useEffect(() => {
        const storedConversations = getStoredConversations();
        setSavedConversations(storedConversations);
    }, [getStoredConversations]);

    // 保存当前对话
    const saveConversation = useCallback((messages: Message[], historyMessages: ChatMessage[]) => {
        if (messages.length === 0) return;

        try {
            // 生成一个新的对话ID
            const id = Date.now().toString();

            // 从用户消息中提取对话标题（使用第一条非空用户消息）
            const firstUserMsg = messages.find(m => m.isUser && m.text.trim().length > 0);
            const title = firstUserMsg
                ? firstUserMsg.text.slice(0, 30) + (firstUserMsg.text.length > 30 ? '...' : '')
                : `对话 ${id}`;

            // 创建新的保存对话对象
            const newConversation: SavedConversation = {
                id,
                title,
                timestamp: Date.now(),
                messages,
                historyMessages
            };

            // 更新状态和持久化存储
            setSavedConversations(prev => {
                const updated = [newConversation, ...prev];
                persistConversations(updated);
                return updated;
            });

            // 显示成功消息
            setSnackbar({
                open: true,
                message: '对话已保存',
                severity: 'success'
            });
        } catch (error) {
            console.error('保存对话失败:', error);
            setSnackbar({
                open: true,
                message: '保存失败，请重试',
                severity: 'error'
            });
        }
    }, [persistConversations, setSnackbar]);

    // 删除保存的对话
    const deleteConversation = useCallback((conversationId: string) => {
        setSavedConversations(prev => {
            const updated = prev.filter(c => c.id !== conversationId);
            persistConversations(updated);
            return updated;
        });

        setSnackbar({
            open: true,
            message: '对话已删除',
            severity: 'success'
        });
    }, [persistConversations, setSnackbar]);

    // 打开对话框
    const openConversationsDialog = useCallback(() => {
        setIsDialogOpen(true);
    }, []);

    return {
        savedConversations,
        isDialogOpen,
        setIsDialogOpen,
        saveConversation,
        deleteConversation,
        openConversationsDialog
    };
}; 